package sample.com.wisdomhealth.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.hyg.lib_base.Net.NetworkOP;
import com.hyg.lib_base.lisener.AppUpdateListener;
import com.hyg.lib_base.mainUtils.LanguageUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.ThirdSDK.PuGongYing;
import com.hyg.lib_common.WebView.WebViewActivity;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.listener.LoginStateListener;
import com.hyg.lib_common.loginpart.LoginActivity;
import com.hyg.lib_common.loginpart.LoginByCodeActivity;
import com.hyg.lib_common.loginpart.LoginFasterActivity;
import com.hyg.lib_common.loginpart.LoginFasterUtil;
import com.hyg.lib_common.loginpart.RegisterActivity;
import com.hyg.lib_common.sweetalertdialog.MyDialog;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.mobile.auth.gatewayauth.ActivityResultListener;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;

import okhttp3.FormBody;
import sample.com.wisdomhealth.R;

@Route(path = Constants.PATH_ACTIVITY_WELCOME)
public class WelcomeActivity extends BaseActivity {
    ProgressBar progressBar;
    String info;
    String app_id = "1108033225";
    public static Tencent mTencent;
    PhoneNumberAuthHelper mAlicomAuthHelper;
    TokenResultListener mTokenListener;
    // IWXAPI 是第三方app和微信通信的openApi接口
    public IWXAPI api;
    private int PrivacyBuilding = -1;
    private MyHandler myHandler = new MyHandler(this);
    LoginFasterUtil loginFasterUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        StatusBarUtil.setTransparent(WelcomeActivity.this);
        check_privacy_policy_building();
        initVersion();
    }

    public void initVersion() {
        TextView version_Tv = findViewById(R.id.tv_version);
        String verName = "2.1.0";
        try {
            verName = getPackageManager().
                    getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        version_Tv.setText("慧中医 V" + verName);
    }

    /**
     * description: 初始化一键登录页面
     *
     * @author visitant
     * @time 2021/4/1 11:57
     */
    public void init() {
        if (!Utils.isEmpty(sn.getString("phone", "")) && !Utils.isEmpty(sn.getString("token", ""))) {
            Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.fade, R.anim.hold);
            finish();
        } else {
            loginFasterUtil = new LoginFasterUtil(this);
            loginFasterUtil.startLoginView(new LoginStateListener() {
                @Override
                public void OnStart(int Type) {
                    Log.i("lgb", "OnStart: " + Type);
                }

                @Override
                public void OnSuccess() {
                    Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.fade, R.anim.hold);
                    finish();
                }

                @Override
                public void OnFail(String Message) {
                    Log.i("lgb", "OnFail: 11111" + Message);
                }

                @Override
                public void OnCancel(String Message) {
                    finishAffinity();
                }

                @Override
                public void OnOpenFail(String Message) {
                    Intent intent = new Intent(WelcomeActivity.this, LoginByCodeActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.fade, R.anim.hold);
                    finish();
                }
            });
        }
    }

    /**
     * description:查询隐私政策最新版本
     *
     * @author visitant
     * @time 2021/4/1 11:56
     */
    public void check_privacy_policy_building() {
        /* 查询隐私政策版本号*/
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .build();
        NetworkOP op = new NetworkOP(str_tag, formBody, myHandler, UrlUtils.PrivacyAddr);
        //使用类的对象op将三个实参发送，通过handler传递参数到NetworkOP中去，在NetworkOP将数据包装发送到规定的互联网地址
        op.okhttpAsyncGet();
    }


    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private WelcomeActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (WelcomeActivity) reference.get();
        }

        public void handleMessage(Message msg) {            //处理隐私政策版本查询返回数据
            switch (msg.what) {
                case 1:
                    ReceiveData receiveData = com.alibaba.fastjson.JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
                    PrivacyBuilding = 1;
                    if (receiveData.getCode().equals("200")) {
                        if (!Utils.isEmpty(receiveData.getData())) {
                            com.alibaba.fastjson.JSONObject data = JSON.parseObject(receiveData.getData());
                            PrivacyBuilding = Integer.parseInt(data.getString("systemVersion"));
                        }
                    }
                    break;

            }
        }
    }

    ;


    /**
     * description: 显示隐私政策
     *
     * @author visitant
     * @time 2021/4/1 11:55
     */
    public void show_privacy_dialog() {
        int saveVersion = ssu.getInt("PrivacyBuild", -1);
        if (saveVersion >= PrivacyBuilding) {
            init();
            return;
        }

        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(com.hyg.lib_common.R.layout.dialog_privacy, null);
        final TextView JumpPrivacyText = view.findViewById(com.hyg.lib_common.R.id.PrivacyName);
        JumpPrivacyText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) return;
                Intent it = new Intent(WelcomeActivity.this, WebViewActivity.class);
                it.putExtra("url", UrlUtils.PrivacyUrl);
                it.putExtra("title", "隐私政策与免责声明");
                it.putExtra("type", "Privacy");
                startActivity(it);
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE);
        pDialog.setTitleText("隐私政策与免责声明");
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("我同意", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                editorn = ssu.edit();
                editorn.putInt("PrivacyBuild", PrivacyBuilding);
                editorn.apply();
                sweetAlertDialog.dismiss();
                init();
            }
        });
        pDialog.setCancelButton("暂不使用", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                finishAffinity();
            }

        });
        pDialog.setCancelable(false);
        pDialog.show();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        check_version_update(false, false);
    }

    /**
     * description:检查app版本更新
     *
     * @param IsShowText      是否提示不再显示
     * @param isSystemSetting 是否是系统检测
     * @author visitant
     * @time 2021/4/1 11:53
     */
    public void check_version_update(final boolean IsShowText, boolean isSystemSetting) {
        new PuGongYing().getUpdateVersion(this, IsShowText, isSystemSetting, new AppUpdateListener() {
            @Override
            public void onStart() {
                AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);
                updateDialog = builder.create();
                updateDialog = new MyDialog(WelcomeActivity.this, com.hyg.lib_common.R.style.alert_dialog_light);
                View dialogView = View.inflate(WelcomeActivity.this, com.hyg.lib_common.R.layout.dialog_update_version, null);
                TextView TvContent = dialogView.findViewById(com.hyg.lib_common.R.id.content_tv);
                TvContent.setText("应用更新中,请稍候...");
                progressBar = dialogView.findViewById(com.hyg.lib_common.R.id.progress_bar);
                updateDialog.setView(dialogView);
                updateDialog.setCancelable(false);
                updateDialog.show();
            }

            @Override
            public void onProgress(int progress) {
                if (progressBar != null) {
                    progressBar.setProgress(progress);
                }
            }

            @Override
            public void onFail() {
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }
                show_privacy_dialog();
            }

            @Override
            public void onSuccess() {
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }
            }

            @Override
            public void onCancel() {
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }
                show_privacy_dialog();
            }

            @Override
            public void onNoUpdateVersion() {
                Log.i("lgb", "onNoUpdateVersion: ");
                show_privacy_dialog();
            }
        });
    }


    @Subscribe
    public void onEvent(EventBusMessage message) {
        //接收以及处理数据
        if (message.getmessage().equals("startMainActivity")) {
            if (loginFasterUtil != null) {
                loginFasterUtil.finishView();
            }
            finish();
        } else if (message.getmessage().equals("finish")) {
            finish();
        }
    }


//    @Override
//    public void finish() {
//        super.finish();
//        finishAffinity();
//    }
}